package core;

import database.User;
import database.UserDb;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by jimmyhsu on 2016/12/17.
 */
public class Login extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = StringUtils.getUtf8String(req.getParameter("username"));
        String password = StringUtils.getUtf8String(req.getParameter("password"));
        resp.setContentType("text/html;charset=gb2312");
        PrintWriter writer = resp.getWriter();

        if (UserDb.userNotExists(username)) {
            req.getSession().invalidate();
            writer.print("<script>alert('该用户不存在');location.href='../view/Admin/login.html';</script>");
        } else {
            User user = UserDb.selectUserById(username);
            if (!password.equals(user.getPassword())
                    || StringUtils.isEmpty(user.getPermission())
                    || !user.getPermission().equals("superadmin")) {
                req.getSession().invalidate();
                writer.print("<script>alert('密码错误');location.href='../view/Admin/login.html';</script>");
            } else {
                req.getSession().setAttribute("login", true);
                req.getSession().setAttribute("username", username);
                req.getSession().setAttribute("password", password);
                writer.print("<script>location.href='../view/Admin/index.jsp';</script>");
            }
        }
    }
}
